import persistentStorage from '../../../utils/storage.js'
const storage = persistentStorage()

export default {
	namespaced: true,
	state: {
		cartList: storage.getSorage('Cart').cartList || []
	},

	getters: {
		// 勾选价格
		allSelectPrice: (state) => {
			return state.cartList.filter(item => item.checked).reduce((prev, item) => {
				return prev + item.num * item.price
			}, 0)
		},
		// 购物车总数量
		allNum: (state) => {
			return state.cartList.reduce((prev, item) => prev += item.num, 0)
		}
	},

	mutations: {
		// 添加购物车
		addGoods: (state, payload) => {
			const filterList = state.cartList.find(item => item.proid === payload.proid)
			if (filterList) {
				filterList.num += payload.num
			} else {
				state.cartList.push(payload)
			}

			storage.setStorage('Cart', state)
		},
		// 单个状态改变
		changeOne: (state, payload) => {
			const filterList = state.cartList.find(item => item.proid === payload.proid)
			if (filterList) filterList.checked = payload.checked

			storage.setStorage('Cart', state)
		},
		// 更改商品数量
		changeGoodsNum: (state, payload) => {
			const filterList = state.cartList.find(item => item.proid === payload.proid)
			if (filterList) filterList.num = payload.num

			storage.setStorage('Cart', state)
		},
		// 删除商品
		delGoods: (state, payload) => {
			state.cartList = state.cartList.filter(item => item.proid != payload)

			storage.setStorage('Cart', state)

		},
		// 全选反选
		changeStatus: (state) => {
			const checked = state.cartList.every(item => item.checked)
			state.cartList.forEach(item => item.checked = !checked)

			storage.setStorage('Cart', state)
		}
	},
	actions: {
		syncDel(context, payload) {
			context.commit('delGoods', payload)
			// console.log(storage.getSorage('Cart'))
		}
	}

}